import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import axios from 'axios'
// 处理异步
export const fetchList = createAsyncThunk('home/fetchList', async () => {
  const res = await axios.get('/api/list')
  console.log('res', res.data.data)
  return res.data.data
})

// count: 1
// goodsName: "积料发些这"
// id: 1
// img: "http://dummyimage.com/100x200/f28779, 全年消交)"
// price: 27

export type CartItemProps = {
  count: number
  goodsName: string
  id: number
  img: string
  price: number
}

export interface InitialStateProps {
  total: number
  list: CartItemProps[]
  cartList: CartItemProps[]
  allPrice: number
}

const initialState: InitialStateProps = {
  total: 0,
  list: [],
  cartList: [],
  allPrice: 0,
}

// reducer
const homeSlice = createSlice({
  name: 'home',
  // 数据仓库
  initialState,
  reducers: {
    // 首页
    toCart(state, action) {
      const goods = state.cartList.find((v) => v.id === action.payload.id)
      if (goods) {
        goods.count++
      } else {
        state.cartList.push(action.payload)
      }
      console.log(action.payload, '----------')
      console.log('state:', state.cartList)
    },
    // 购物车页面
    addItemCart(state, action) {
      const goods = state.cartList.find((v) => v.id === action.payload.id)
      if (goods) {
        goods.count++
      }
    },

    reduceItemCart(state, action) {
      const goods = state.cartList.find((v) => v.id === action.payload.id)
      if (goods) {
        goods.count--
      }
    },
  },
  // 监听异步
  extraReducers(builder) {
    builder.addCase(fetchList.pending, () => {})
    builder.addCase(fetchList.fulfilled, (state, action) => {
      state.total = action.payload.total
      state.list = action.payload.list
      console.log('state', state.list)
    })
  },
})

export default homeSlice.reducer

export const { toCart, addItemCart, reduceItemCart } = homeSlice.actions
